package com.jfinal.ext.util;

import com.jfinal.log.Log;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author Timor
 * @version 1.0
 * @date 2023/01/06 11:13:24
 */
public enum ImageUtil {;
    private static final Log LOG = Log.getLog(ImageUtil.class);

    public static BufferedImage compress(@NotNull BufferedImage image,
                                         @Range(from = 0, to = 1) float ratio,
                                         int scale) {
        final int width = image.getWidth(null);
        final int height = image.getHeight(null);
        final int newWidth = (int) (width * ratio);
        final int newHeight = (int) (height * ratio);

        final Image instance = image.getScaledInstance(newWidth, newHeight, scale);
        final BufferedImage temp = new BufferedImage(
                newWidth, newHeight, image.getType());

        temp.getGraphics().drawImage(instance, 0, 0, null);

        return temp;
    }

    public static boolean write(@NotNull RenderedImage image,
                                @NotNull String formatName,
                                @NotNull File output) {
        boolean success = false;

        try {
            success = ImageIO.write(image, formatName, output);
        } catch (IOException e) {
            LOG.warn("write image error", e);
        }

        return success;
    }

}
